# from pymysql import Connection
# # 获取MySQL数据库的链接对象
# conn=Connection(
#     host='localhost', # 主机名或IP地址
#     port=3306, # 默认端口3306
#     user='root',    # 用户名
#     password='1234', # 密码
# )
# # 获取游标对象
# cursor=conn.cursor()
# conn.select_db('tmstest') # 选择数据库
# # 使用游标对象，执行sql语句
# cursor.execute("INSERT INTO user(username,email, password) VALUES ('pytest','123@123.com', '123456')")
# conn.commit() # 提交事务
# cursor.execute('SELECT * FROM user')
# # 获取查询结果
# result=cursor.fetchall()
# # 打印查询结果
# for row in result:
#     print(row)
# # 关闭游标和链接
# print(conn.get_server_info()) # 打印链接信息

# 使用python代码读取数据库数据，以json格式写入到pout.txt文件中
from pymysql import Connection
import json
conn=Connection(
    host='localhost', # 主机名或IP地址
    port=3306, # 默认端口3306
    user='root',    # 用户名
    password='1234', # 密码
    database='tmstest', # 数据库名
    autocommit=True # 设置自动提交事务
)
cursor=conn.cursor()
cursor.execute('SELECT * FROM user')
result=cursor.fetchall()
data=[]
for row in result:
    data.append(dict(zip(['id', 'username', 'email', 'password'], row)))
data=json.dumps(data, indent=2,ensure_ascii=False)
print(data)
with open('pout.txt', 'w', encoding='utf-8') as f:
    f.write(data)
conn.close()
